package com.leet.tree;

import java.util.Arrays;

public class BuildTree {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length == 0 || inorder.length == 0){
            return null;
        }
        TreeNode root = new TreeNode(preorder[0]);
        for (int i = 0; i < preorder.length; i++) {
            if(inorder[i] == preorder[0]){
                int[] pre_l = Arrays.copyOfRange(preorder,1,i+1);
                int[] pre_r = Arrays.copyOfRange(preorder,i+1,preorder.length);
                int[] in_l = Arrays.copyOfRange(inorder,0,i);
                int[] in_r = Arrays.copyOfRange(inorder,i+1,inorder.length);
                root.left = buildTree(pre_l,in_l);
                root.right = buildTree(pre_r,in_r);
                // 及时break；
            }
        }
        return root;
    }
}
